import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiBody,
} from '@nestjs/swagger';
import type { User, LoginCredentials } from './user.interface';
import { UserService } from './user.service';

@ApiTags('用户管理')
@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @ApiOperation({ summary: '获取用户列表' })
  @ApiResponse({ status: 200, description: '成功获取用户列表' })
  @ApiBearerAuth()
  @Get()
  findAll(): User[] {
    return this.userService.findAll();
  }

  @ApiOperation({ summary: '根据ID获取用户信息' })
  @ApiResponse({ status: 200, description: '成功获取用户信息' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  @ApiBearerAuth()
  @Get(':id')
  findOne(@Param('id') id: string): User {
    const user = this.userService.findById(id);
    if (!user) {
      throw new Error('User not found');
    }
    return user;
  }

  @ApiOperation({ summary: '创建用户' })
  @ApiResponse({ status: 201, description: '用户创建成功' })
  @ApiBody({ type: () => Object, description: '用户数据' })
  @Post()
  @HttpCode(HttpStatus.CREATED)
  create(@Body() userData: Partial<User>): User {
    return this.userService.create(userData);
  }

  @ApiOperation({ summary: '更新用户' })
  @ApiResponse({ status: 200, description: '用户更新成功' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  @ApiBearerAuth()
  @ApiBody({ type: () => Object, description: '用户更新数据' })
  @Put(':id')
  update(
    @Param('id') id: string,
    @Body() userData: Partial<User>,
  ): User {
    const result = this.userService.update(id, userData);
    if (!result) {
      throw new Error('User not found');
    }
    return result;
  }

  @ApiOperation({ summary: '删除用户' })
  @ApiResponse({ status: 204, description: '用户删除成功' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  @ApiBearerAuth()
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  remove(@Param('id') id: string): void {
    const result = this.userService.delete(id);
    if (!result) {
      throw new Error('User not found');
    }
  }

  @ApiOperation({ summary: '用户登录' })
  @ApiResponse({ status: 200, description: '登录成功' })
  @ApiResponse({ status: 401, description: '用户名或密码错误' })
  @ApiBody({ type: () => Object, description: '登录凭据' })
  @Post('login')
  login(@Body() credentials: LoginCredentials): { user: User; token: string } {
    const result = this.userService.login(credentials);
    if (!result) {
      throw new Error('Invalid credentials');
    }
    return result;
  }

  @ApiOperation({ summary: '获取用户登录记录' })
  @ApiResponse({ status: 200, description: '成功获取登录记录' })
  @ApiBearerAuth()
  @Get(':id/login-records')
  getLoginRecords(@Param('id') id: string): any[] {
    return this.userService.getLoginRecords(id);
  }
}